<template>
  <div class="order-payment">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>库存盘点</h1>
      <div class="breadcrumb">仓库管理 > 库存盘点</div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>盘点单号</label>
          <input v-model="searchForm.countCode" type="text" placeholder="请输入盘点单号" @input="onSearchInput" />
        </div>
        <div class="form-item">
          <label>仓库</label>
          <select v-model="searchForm.warehouseId" @change="fetchStockCountList">
            <option value="">全部</option>
            <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
          </select>
        </div>
        <div class="form-item">
          <label>状态</label>
          <select v-model="searchForm.status" @change="fetchStockCountList">
            <option value="">全部</option>
            <option :value="0">待提交</option>
            <option :value="1">待审核</option>
            <option :value="2">已审核</option>
            <option :value="3">已完成</option>
            <option :value="4">已驳回</option>
          </select>
        </div>
        <div class="form-buttons">
          <button class="btn btn-primary" @click="fetchStockCountList">查询</button>
          <button class="btn btn-secondary" @click="resetSearch">重置</button>
        </div>
      </div>
    </div>

    <!-- 搜索状态提示 -->
    <div class="search-status" v-if="hasActiveFilters">
      <div class="status-text">
        <span class="filter-icon">🔍</span>
        当前筛选条件：
        <span v-if="searchForm.countCode" class="filter-tag">盘点单号: {{ searchForm.countCode }}</span>
        <span v-if="searchForm.warehouseId" class="filter-tag">仓库: {{ getWarehouseName(searchForm.warehouseId) }}</span>
        <span v-if="searchForm.status !== ''" class="filter-tag">状态: {{ getStatusText(searchForm.status) }}</span>
        <button class="clear-filters" @click="resetSearch">清除筛选</button>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <div class="action-left">
        <button class="btn btn-primary" @click="handleCreate">手动创建盘点单</button>
        <button class="btn btn-success" @click="handleGenerateTask">自动生成盘点任务</button>
      </div>
      <div class="action-right">
        <button 
          class="btn btn-warning" 
          @click="handleBatchSubmitAudit" 
          :disabled="selectedItems.length === 0"
        >
          <span class="btn-icon">📋</span>
          提交审核 ({{ selectedItems.length }})
        </button>
      </div>
    </div>

    <!-- 盘点单列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
        <tr>
          <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll" /></th>
          <th>盘点单号</th>
          <th>仓库</th>
          <th>商品数量</th>
          <th>差异数量</th>
          <th>状态</th>
          <th>创建人</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in stockCountList" :key="item.id" :class="{ 'row-selected': item.selected }">
          <td>
            <input 
              type="checkbox" 
              v-model="item.selected" 
              @change="updateSelectedItems"
              :disabled="item.status !== 0 && item.status !== 4"
            />
          </td>
          <td>{{ item.countCode }}</td>
          <td>{{ getWarehouseName(item.warehouseId) }}</td>
          <td>{{ item.itemCount || 0 }}</td>
          <td :class="getDiffClass(item.totalDiff)">{{ formatDiff(item.totalDiff) }}</td>
          <td>
            <span :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</span>
          </td>
          <td>{{ item.createdBy || '-' }}</td>
          <td>{{ formatDate(item.createdAt) }}</td>
          <td>
            <button class="btn btn-small btn-info" @click="handleView(item)">查看</button>
            <button v-if="item.status === 4" class="btn btn-small btn-warning" @click="handleEdit(item)">编辑</button>
            <button v-if="item.status === 0" class="btn btn-small btn-danger" @click="handleDelete(item.id)">删除</button>
          </td>
        </tr>
        <tr v-if="stockCountList.length === 0">
          <td colspan="9" class="text-center">暂无数据</td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="pagination.total > 0">
      <div class="pagination-info">
        共{{ Math.ceil(pagination.total / pagination.size) }}页/{{ pagination.total }}条数据
      </div>
      <div class="pagination-controls">
        <button class="btn btn-page" :disabled="pagination.current === 1" @click="changePage(pagination.current - 1)">上一页</button>
        <button
            v-for="page in visiblePages"
            :key="page"
            class="btn btn-page"
            :class="{ active: page === pagination.current }"
            @click="changePage(page)"
        >
          {{ page }}
        </button>
        <button class="btn btn-page" :disabled="pagination.current === Math.ceil(pagination.total / pagination.size)" @click="changePage(pagination.current + 1)">下一页</button>
      </div>
      <div class="pagination-jump">
        <span>跳至</span>
        <input type="number" v-model="jumpPage" min="1" :max="Math.ceil(pagination.total / pagination.size)" />
        <span>页</span>
        <button class="btn btn-small" @click="jumpToPage">确定</button>
      </div>
    </div>

    <!-- 盘点单详情对话框 -->
    <div v-if="detailDialog.visible" class="modal-overlay" @click="detailDialog.visible = false">
      <div class="modal-content" style="width: 90%;" @click.stop>
        <div class="modal-header">
          <h3>盘点单详情</h3>
          <button class="modal-close" @click="detailDialog.visible = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="detail-header">
            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">盘点单号：</span>
                <span>{{ detailDialog.data.stockCount?.countCode || '' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">仓库：</span>
                <span>{{ getWarehouseName(detailDialog.data.stockCount?.warehouseId) }}</span>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">状态：</span>
                <span :class="getStatusClass(detailDialog.data.stockCount?.status)">
                  {{ getStatusText(detailDialog.data.stockCount?.status) }}
                </span>
              </div>
              <div class="detail-item">
                <span class="detail-label">创建人：</span>
                <span>{{ detailDialog.data.stockCount?.createdBy || '-' }}</span>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">创建时间：</span>
                <span>{{ formatDate(detailDialog.data.stockCount?.createdAt) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">审核时间：</span>
                <span>{{ formatDate(detailDialog.data.stockCount?.approvedAt) }}</span>
              </div>
            </div>
          </div>

          <div class="detail-content">
            <h3>盘点明细</h3>
            <table class="data-table">
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th>商品编码</th>
                  <th>批次号</th>
                  <th>库位</th>
                  <th>系统数量</th>
                  <th>盘点数量</th>
                  <th>差异数量</th>
                  <th>差异状态</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in detailDialog.data.items || []" :key="index">
                  <td>{{ getProductName(item.skuId) }}</td>
                  <td>{{ getSkuCode(item.skuId) }}</td>
                  <td>{{ item.batchNo || '-' }}</td>
                  <td>{{ getLocationName(item.locationId) }}</td>
                  <td>{{ item.systemQty }}</td>
                  <td>{{ item.countQty }}</td>
                  <td :class="getDiffClass(item.diffQty)">{{ formatDiff(item.diffQty) }}</td>
                  <td>
                    <span :class="getDiffStatusClass(item.diffQty)">{{ getDiffStatusText(item.diffQty) }}</span>
                  </td>
                </tr>
                <tr v-if="(detailDialog.data.items || []).length === 0">
                  <td colspan="8" class="text-center">暂无数据</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="detailDialog.visible = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- 新建盘点单对话框 -->
    <div v-if="createDialog.visible" class="modal-overlay" @click="createDialog.visible = false">
      <div class="modal-content" style="width: 80%;" @click.stop>
        <div class="modal-header">
          <h3>新建盘点单</h3>
          <button class="modal-close" @click="createDialog.visible = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>盘点单号</label>
            <input type="text" v-model="createDialog.form.countCode" placeholder="请输入盘点单号" />
          </div>
          <div class="form-group">
            <label>盘点仓库</label>
            <select v-model="createDialog.form.warehouseId">
              <option value="">请选择仓库</option>
              <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
            </select>
          </div>
          <div class="form-group">
            <label>创建人</label>
            <input type="text" v-model="createDialog.form.createdBy" placeholder="请输入创建人" />
          </div>

          <div class="divider">
            <span>盘点商品</span>
          </div>
        
          <div class="items-container">
            <table class="data-table">
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th>系统数量</th>
                  <th>盘点数量</th>
                  <th>差异</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in createDialog.form.items" :key="index">
                  <td>
                    <select v-model="item.skuId" @change="() => handleProductSelect(item.skuId, index)">
                      <option value="">请选择商品</option>
                      <option v-for="prod in products" :key="prod.id" :value="prod.id">{{ prod.productName }}</option>
                    </select>
                  </td>
                  <td>
                    <input type="number" v-model="item.systemQty" step="0.01" min="0" placeholder="系统数量" readonly />
                  </td>
                  <td>
                    <input type="number" v-model="item.countQty" step="0.01" min="0" placeholder="盘点数量" @input="() => calculateDiff(index)" />
                  </td>
                  <td :class="getDiffClass(item.diffQty)">
                    {{ formatDiff(item.diffQty) }}
                  </td>
                  <td>
                    <button v-if="index === 0" class="btn btn-small btn-success" @click="addItemRow">添加</button>
                    <button v-else class="btn btn-small btn-danger" @click="removeItemRow(index)">删除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="createDialog.visible = false">取消</button>
          <button class="btn btn-primary" @click="submitStockCount" :disabled="createDialog.loading">确认</button>
        </div>
      </div>
    </div>

    <!-- 生成盘点任务对话框 -->
    <div v-if="generateDialog.visible" class="modal-overlay" @click="generateDialog.visible = false">
      <div class="modal-content" style="width: 500px;" @click.stop>
        <div class="modal-header">
          <h3>生成盘点任务</h3>
          <button class="modal-close" @click="generateDialog.visible = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>选择仓库</label>
            <select v-model="generateDialog.warehouseId">
              <option value="">请选择仓库</option>
              <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
            </select>
          </div>
          <div class="generate-info">
            <p>🔍 系统将自动扫描该仓库的所有库存商品</p>
            <p>📋 生成对应的盘点明细项</p>
            <p>⚡ 您只需要录入实际盘点数量即可</p>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="generateDialog.visible = false">取消</button>
          <button class="btn btn-primary" @click="submitGenerateTask" :disabled="!generateDialog.warehouseId">生成任务</button>
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <div v-if="editDialog.visible" class="modal-overlay" @click="editDialog.visible = false">
      <div class="modal-content" style="width: 80%;" @click.stop>
        <div class="modal-header">
          <h3>编辑盘点单 - {{ editDialog.data.stockCount?.countCode }}</h3>
          <button class="modal-close" @click="editDialog.visible = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>盘点单号</label>
            <input type="text" v-model="editDialog.form.countCode" readonly />
          </div>
          <div class="form-group">
            <label>盘点仓库</label>
            <select v-model="editDialog.form.warehouseId">
              <option value="">请选择仓库</option>
              <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
            </select>
          </div>
          <div class="form-group">
            <label>创建人</label>
            <input type="text" v-model="editDialog.form.createdBy" placeholder="请输入创建人" />
          </div>

          <div class="divider">
            <span>盘点商品</span>
          </div>
        
          <div class="items-container">
            <table class="data-table">
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th>系统数量</th>
                  <th>盘点数量</th>
                  <th>差异</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in editDialog.form.items" :key="index">
                  <td>
                    <select v-model="item.skuId" @change="() => handleEditProductSelect(item.skuId, index)">
                      <option value="">请选择商品</option>
                      <option v-for="prod in products" :key="prod.id" :value="prod.id">{{ prod.productName }}</option>
                    </select>
                  </td>
                  <td>
                    <input type="number" v-model="item.systemQty" step="0.01" min="0" placeholder="系统数量" readonly />
                  </td>
                  <td>
                    <input type="number" v-model="item.countQty" step="0.01" min="0" placeholder="盘点数量" @input="() => calculateEditDiff(index)" />
                  </td>
                  <td>
                    <input type="number" v-model="item.diffQty" step="0.01" placeholder="差异" readonly />
                  </td>
                  <td>
                    <button v-if="index === 0" class="btn btn-small btn-success" @click="addEditItemRow">添加</button>
                    <button v-else class="btn btn-small btn-danger" @click="removeEditItemRow(index)">删除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="editDialog.visible = false">取消</button>
          <button class="btn btn-primary" @click="submitEdit" :disabled="editDialog.loading">保存修改</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { apiGet, apiPost, apiPut, apiDelete } from '../../utils/api.js'

// 响应式数据
const stockCountList = ref([])
const warehouses = ref([])
const products = ref([])
const selectAll = ref(false)
const jumpPage = ref(1)
const selectedItems = ref([])
let searchTimeout = null

// 搜索表单
const searchForm = reactive({
  countCode: '',
  warehouseId: '',
  status: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  loading: false,
  data: {}
})

// 创建对话框
const createDialog = reactive({
  visible: false,
  loading: false,
  form: {
    countCode: '',
    warehouseId: '',
    createdBy: '',
    items: [{ skuId: '', systemQty: 0, countQty: 0, diffQty: 0 }]
  }
})

// 生成任务对话框
const generateDialog = reactive({
  visible: false,
  warehouseId: ''
})

// 编辑对话框
const editDialog = reactive({
  visible: false,
  loading: false,
  data: {},
  form: {
    countCode: '',
    warehouseId: '',
    createdBy: '',
    items: [{ skuId: '', systemQty: 0, countQty: 0, diffQty: 0 }]
  }
})

// 修改状态跟踪
const modifiedItems = ref(new Set())

// 检查是否有活跃的筛选条件
const hasActiveFilters = computed(() => {
  return searchForm.countCode || 
         searchForm.warehouseId || 
         searchForm.status !== ''
})

// 计算可见页码
const visiblePages = computed(() => {
  const currentPage = pagination.current
  const totalPages = Math.ceil(pagination.total / pagination.size)
  
  if (totalPages <= 5) {
    return Array.from({ length: totalPages }, (_, i) => i + 1)
  }
  
  if (currentPage <= 3) {
    return [1, 2, 3, 4, 5]
  }
  
  if (currentPage >= totalPages - 2) {
    return [totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages]
  }
  
  return [currentPage - 2, currentPage - 1, currentPage, currentPage + 1, currentPage + 2]
})

// 获取盘点单列表
const fetchStockCountList = async () => {
  try {
    const params = new URLSearchParams({
        page: pagination.current,
        size: pagination.size,
      ...(searchForm.countCode && { countCode: searchForm.countCode }),
      ...(searchForm.warehouseId && { warehouseId: searchForm.warehouseId }),
      ...(searchForm.status !== '' && { status: searchForm.status })
    })

    const data = await apiGet(`/ware-service/ware/stock-count/list?${params}`)
    
    if (data.records) {
      stockCountList.value = data.records.map(item => ({
        ...item,
        selected: false,
        itemCount: Math.floor(Math.random() * 20) + 5, // 模拟商品数量
        totalDiff: (Math.random() - 0.5) * 20 // 模拟差异数量
      }))
      pagination.total = data.total || 0
      pagination.current = data.current || 1
    } else {
      stockCountList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取盘点单列表失败:', error)
    stockCountList.value = []
    pagination.total = 0
  }
}

// 实时搜索输入处理
const onSearchInput = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  
  searchTimeout = setTimeout(() => {
    pagination.current = 1
    fetchStockCountList()
  }, 500)
}

// 重置搜索
const resetSearch = () => {
  searchForm.countCode = ''
  searchForm.warehouseId = ''
  searchForm.status = ''
  pagination.current = 1
  fetchStockCountList()
}

// 页码切换
const changePage = (page) => {
  if (page < 1 || page > Math.ceil(pagination.total / pagination.size)) return
  pagination.current = page
  fetchStockCountList()
}

// 页码跳转
const jumpToPage = () => {
  const page = Number(jumpPage.value)
  if (page && page >= 1 && page <= Math.ceil(pagination.total / pagination.size)) {
    pagination.current = page
    fetchStockCountList()
  }
}

// 全选/取消全选
const toggleSelectAll = () => {
  stockCountList.value.forEach(item => {
    // 待提交和已驳回状态的盘点单才能被选中
    if (item.status === 0 || item.status === 4) {
      item.selected = selectAll.value
    }
  })
  updateSelectedItems()
}

// 更新选中项目
const updateSelectedItems = () => {
  selectedItems.value = stockCountList.value.filter(item => item.selected && (item.status === 0 || item.status === 4))
}

// 获取仓库名称
const getWarehouseName = (id) => {
  if (!id) return '-'
  const warehouse = warehouses.value.find(w => w.id === id)
  return warehouse ? warehouse.whName : '-'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待提交',
    1: '待审核',
    2: '已审核',
    3: '已完成',
    4: '已驳回'
  }
  return statusMap[status] || '未知'
}

// 获取状态类名
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-info',
    1: 'status-warning',
    2: 'status-success',
    3: 'status-success',
    4: 'status-danger'
  }
  return `status ${classMap[status] || ''}`
}

// 获取差异类名
const getDiffClass = (diff) => {
  if (!diff || diff === 0) return ''
  return diff > 0 ? 'text-success' : 'text-danger'
}

// 格式化差异数量
const formatDiff = (diff) => {
  if (!diff || diff === 0) return '0'
  return diff > 0 ? `+${diff}` : `${diff}`
}

// 获取差异状态类名
const getDiffStatusClass = (diff) => {
  if (!diff || diff === 0) return 'status-normal'
  return diff > 0 ? 'status-increase' : 'status-decrease'
}

// 获取差异状态文本
const getDiffStatusText = (diff) => {
  if (!diff || diff === 0) return '无差异'
  return diff > 0 ? '盘盈' : '盘亏'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

// 查看盘点单详情
const handleView = async (row) => {
  detailDialog.visible = true
  detailDialog.loading = true
  detailDialog.data = {}
  
  try {
    const result = await apiGet(`/ware-service/ware/stock-count/${row.id}`)
    detailDialog.data = result || {}
  } catch (error) {
    console.error('获取盘点单详情失败:', error)
  } finally {
    detailDialog.loading = false
  }
}

// 新建盘点单
const handleCreate = () => {
  createDialog.visible = true
  createDialog.form = {
    countCode: `SC${new Date().getTime()}`,
    warehouseId: '',
    createdBy: '当前用户',
    items: [{ skuId: '', systemQty: 0, countQty: 0, diffQty: 0 }]
  }
}

// 生成盘点任务
const handleGenerateTask = () => {
  generateDialog.visible = true
  generateDialog.warehouseId = ''
}

// 提交生成任务
const submitGenerateTask = async () => {
  try {
    const result = await apiPost('/ware-service/ware/stock-count/generate', {
      warehouseId: generateDialog.warehouseId
    })
    
    if (result && (result.code === 0 || result.status === 200 || result.success)) {
      alert('盘点任务生成成功')
      generateDialog.visible = false
      await fetchStockCountList()
    } else {
      alert('盘点任务生成失败')
    }
  } catch (error) {
    console.error('生成盘点任务失败:', error)
    alert('生成盘点任务失败')
  }
}

// 批量提交审核
const handleBatchSubmitAudit = async () => {
  if (selectedItems.value.length === 0) {
    alert('请选择需要提交审核的盘点单')
    return
  }
  
  // 检查是否有驳回状态的单据未修改
  const rejectedItems = selectedItems.value.filter(item => item.status === 4)
  const unmodifiedRejectedItems = rejectedItems.filter(item => !modifiedItems.value.has(item.id))
  
  if (unmodifiedRejectedItems.length > 0) {
    const itemCodes = unmodifiedRejectedItems.map(item => item.countCode).join('、')
    alert(`以下已驳回的盘点单必须先进行修改才能提交审核：${itemCodes}\n请先点击"编辑"按钮修改单据内容`)
    return
  }
  
  if (confirm(`确定要将选中的 ${selectedItems.value.length} 个盘点单提交审核吗？`)) {
    try {
      const promises = selectedItems.value.map(item => 
        apiPost(`/ware-service/ware/stock-count/${item.id}/submit`)
      )
      
      await Promise.all(promises)
      alert(`成功提交 ${selectedItems.value.length} 个盘点单到审核队列`)
      
      // 提交成功后，移除修改标记
      selectedItems.value.forEach(item => {
        modifiedItems.value.delete(item.id)
      })
      
      await fetchStockCountList()
      selectedItems.value = []
      selectAll.value = false
    } catch (error) {
      console.error('批量提交审核失败:', error)
      alert('批量提交审核失败')
    }
  }
}

// 删除盘点单
const handleDelete = async (id) => {
  if (confirm('确定要删除此盘点单吗？')) {
    try {
      const result = await apiDelete(`/ware-service/ware/stock-count/${id}`)
      if (result && (result.code === 0 || result.status === 200 || result.status === 204 || result.success)) {
        alert('盘点单删除成功')
        await fetchStockCountList()
      } else {
        alert('盘点单删除失败')
      }
    } catch (error) {
      console.error('删除盘点单失败:', error)
      alert('删除盘点单失败')
    }
  }
}



// 添加商品行
const addItemRow = () => {
  createDialog.form.items.push({ skuId: '', systemQty: 0, countQty: 0, diffQty: 0 })
}

// 删除商品行
const removeItemRow = (index) => {
  createDialog.form.items.splice(index, 1)
}

// 商品选择事件
const handleProductSelect = async (skuId, index) => {
  if (skuId && createDialog.form.warehouseId) {
    // 这里可以调用API获取该商品在该仓库的系统库存
    // 暂时使用模拟数据
    createDialog.form.items[index].systemQty = Math.floor(Math.random() * 100) + 10
    calculateDiff(index)
  }
}

// 计算差异
const calculateDiff = (index) => {
  const item = createDialog.form.items[index]
  item.diffQty = (item.countQty || 0) - (item.systemQty || 0)
}

// 提交盘点单
const submitStockCount = async () => {
  // 表单验证
  if (!createDialog.form.countCode) {
    alert('请输入盘点单号')
    return
  }
  
  if (!createDialog.form.warehouseId) {
    alert('请选择盘点仓库')
    return
  }
  
  if (createDialog.form.items.some(item => !item.skuId)) {
    alert('请选择所有商品')
    return
  }
    
  createDialog.loading = true
  
  try {
    const submitData = {
      ...createDialog.form,
      items: createDialog.form.items.filter(item => item.skuId)
    }
    
    const result = await apiPost('/ware-service/ware/stock-count', submitData)
    if (result && (result.code === 0 || result.status === 200 || result.status === 201 || result.success)) {
      alert('盘点单创建成功')
      createDialog.visible = false
      await fetchStockCountList()
    } else {
      alert('盘点单创建失败')
    }
  } catch (error) {
    console.error('创建盘点单失败:', error)
    alert('创建盘点单失败')
  } finally {
    createDialog.loading = false
  }
}

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const params = new URLSearchParams({
      page: 1,
      size: 100
    })
    
    const data = await apiGet(`/ware-service/warehouse/list?${params}`)
    
    if (data.records) {
      warehouses.value = data.records || []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    warehouses.value = []
  }
}

// 获取商品列表
const fetchProducts = async () => {
  try {
    const params = new URLSearchParams({
      page: 1,
      size: 100
    })
    
    const data = await apiGet(`/ware-service/ware/sku/list?${params}`)
    
    if (data.records) {
      products.value = data.records || []
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    products.value = []
  }
}

// 打开编辑对话框
const handleEdit = async (item) => {
  editDialog.visible = true
  editDialog.loading = true
  editDialog.data = {}
  
  try {
    const result = await apiGet(`/ware-service/ware/stock-count/${item.id}`)
    editDialog.data = result || {}
    
    // 填充编辑表单
    if (editDialog.data.stockCount) {
      editDialog.form.countCode = editDialog.data.stockCount.countCode || ''
      editDialog.form.warehouseId = editDialog.data.stockCount.warehouseId || ''
      editDialog.form.createdBy = editDialog.data.stockCount.createdBy || ''
    }
    
    // 填充商品明细
    if (editDialog.data.items && editDialog.data.items.length > 0) {
      editDialog.form.items = editDialog.data.items.map(item => ({
        skuId: item.skuId || '',
        systemQty: item.systemQty || 0,
        countQty: item.countQty || 0,
        diffQty: item.diffQty || 0
      }))
    } else {
      editDialog.form.items = [{ skuId: '', systemQty: 0, countQty: 0, diffQty: 0 }]
    }
  } catch (error) {
    console.error('获取盘点单详情失败:', error)
  } finally {
    editDialog.loading = false
  }
}

// 编辑商品选择处理
const handleEditProductSelect = async (skuId, index) => {
  if (skuId) {
    try {
      // 获取商品库存信息
      const inventoryData = await apiGet(`/ware-service/inventory/by-sku/${skuId}`)
      if (inventoryData && inventoryData.length > 0) {
        const totalQty = inventoryData.reduce((sum, inv) => sum + (inv.onHandQty || 0), 0)
        editDialog.form.items[index].systemQty = totalQty
        editDialog.form.items[index].countQty = totalQty
        calculateEditDiff(index)
      }
    } catch (error) {
      console.error('获取商品库存失败:', error)
      editDialog.form.items[index].systemQty = 0
      editDialog.form.items[index].countQty = 0
      editDialog.form.items[index].diffQty = 0
    }
  }
}

// 计算编辑差异
const calculateEditDiff = (index) => {
  const item = editDialog.form.items[index]
  if (item.systemQty !== undefined && item.countQty !== undefined) {
    item.diffQty = item.countQty - item.systemQty
  }
}

// 添加编辑商品行
const addEditItemRow = () => {
  editDialog.form.items.push({ skuId: '', systemQty: 0, countQty: 0, diffQty: 0 })
}

// 删除编辑商品行
const removeEditItemRow = (index) => {
  if (editDialog.form.items.length > 1) {
    editDialog.form.items.splice(index, 1)
  }
}

// 提交编辑
const submitEdit = async () => {
  if (!editDialog.form.warehouseId) {
    alert('请选择盘点仓库')
    return
  }
  
  if (!editDialog.form.items.some(item => item.skuId)) {
    alert('请至少添加一个商品')
    return
  }
  
  editDialog.loading = true
  
  try {
    const id = editDialog.data.stockCount?.id
    const result = await apiPut(`/ware-service/ware/stock-count/${id}`, {
      countCode: editDialog.form.countCode,
      warehouseId: editDialog.form.warehouseId,
      createdBy: editDialog.form.createdBy,
      items: editDialog.form.items.map(item => ({
        skuId: item.skuId,
        systemQty: item.systemQty,
        countQty: item.countQty,
        diffQty: item.diffQty
      }))
    })
    
    if (result && (result.code === 0 || result.status === 200 || result.success)) {
      alert('盘点单修改成功')
      // 标记该单据为已修改
      modifiedItems.value.add(id)
      editDialog.visible = false
      await fetchStockCountList()
    } else {
      alert('修改失败')
    }
  } catch (error) {
    console.error('修改盘点单失败:', error)
    alert('修改失败')
  } finally {
    editDialog.loading = false
  }
}

// 根据SKU ID获取商品名称
const getProductName = (skuId) => {
  const product = products.value.find(p => p.id === skuId)
  return product ? product.productName : '未知商品'
}

// 根据SKU ID获取SKU编码
const getSkuCode = (skuId) => {
  const product = products.value.find(p => p.id === skuId)
  return product ? product.skuCode : '-'
}

// 获取库位名称
const getLocationName = (locationId) => {
  if (!locationId) return '-'
  return `库位-${locationId}`
}

// 生命周期
onMounted(() => {
  fetchStockCountList()
  fetchWarehouses()
  fetchProducts()
})
</script>

<style scoped>
.order-payment {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.breadcrumb {
  color: #666;
  font-size: 14px;
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
}

.form-item label {
  font-size: 14px;
  margin-bottom: 5px;
  color: #333;
}

.form-item input,
.form-item select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-buttons {
  display: flex;
  gap: 10px;
  align-items: flex-end;
  margin-top: 24px;
}

/* 搜索状态提示 */
.search-status {
  background: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 6px;
  padding: 12px 16px;
  margin-bottom: 20px;
}

.status-text {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.filter-icon {
  font-size: 16px;
}

.filter-tag {
  background: #fa8c16;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
}

.clear-filters {
  background: #ff4d4f;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  margin-left: auto;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-left {
  display: flex;
  gap: 10px;
}

.action-right {
  display: flex;
  gap: 10px;
}

.btn-icon {
  margin-right: 6px;
}

.row-selected {
  background-color: #e6f7ff !important;
}

.table-container {
  margin-bottom: 20px;
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: left;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: bold;
}

.data-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.text-center {
  text-align: center;
}

.text-success {
  color: #52c41a;
  font-weight: 500;
}

.text-danger {
  color: #ff4d4f;
  font-weight: 500;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-info {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-warning {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-success {
  background-color: #e6fffb;
  color: #13c2c2;
}

.status-primary {
  background-color: #f0f5ff;
  color: #2f54eb;
}

.status-danger {
  background-color: #fff2f0;
  color: #ff4d4f;
}

/* 差异状态样式 */
.status-normal {
  background-color: #f0f0f0;
  color: #666;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.status-increase {
  background-color: #f6ffed;
  color: #52c41a;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.status-decrease {
  background-color: #fff2f0;
  color: #ff4d4f;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination-jump input {
  width: 50px;
  padding: 4px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary {
  background-color: #1890ff;
  color: white;
}

.btn-secondary {
  background-color: #f5f5f5;
  color: #333;
}

.btn-success {
  background-color: #52c41a;
  color: white;
}

.btn-info {
  background-color: #1890ff;
  color: white;
}

.btn-danger {
  background-color: #ff4d4f;
  color: white;
}

.btn-warning {
  background-color: #fa8c16;
  color: white;
}

.btn-small {
  padding: 4px 8px;
  font-size: 12px;
}

.btn-page {
  padding: 4px 10px;
  min-width: 30px;
  background-color: #fff;
  border: 1px solid #ddd;
}

.btn-page.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ddd;
}

.modal-header h3 {
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #ddd;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.divider::before,
.divider::after {
  content: "";
  flex-grow: 1;
  height: 1px;
  background-color: #ddd;
}

.divider span {
  padding: 0 10px;
  color: #666;
  font-size: 14px;
}

.items-container {
  margin-top: 16px;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.detail-item {
  flex: 1;
  min-width: 250px;
  padding-right: 20px;
}

.detail-label {
  font-weight: bold;
  color: #666;
}

.detail-content {
  margin-top: 20px;
}

.detail-content h3 {
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}

.generate-info {
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 6px;
  padding: 16px;
  margin-top: 16px;
}

.generate-info p {
  margin: 8px 0;
  color: #52c41a;
  font-size: 14px;
}
</style>
